package com.rongke.web.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.commons.PageDto;
import com.rongke.mapper.CashRecordMapper;
import com.rongke.model.Admin;
import com.rongke.model.CashRecord;
import com.rongke.model.User;
import com.rongke.model.UserAuthMsg;
import com.rongke.service.AdminService;
import com.rongke.service.CashRecordService;

import com.rongke.service.UserAuthMsgService;
import com.rongke.service.UserService;
import com.rongke.utils.OrderUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @version : Ver 1.0
 * @CashRecordController
 * @用户商家现金流水Controller
 */
@RestController
@RequestMapping(value = "/api/cashRecord")
@Transactional
@CrossOrigin
public class CashRecordController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private CashRecordService cashRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserAuthMsgService userAuthMsgService;
    /**
     * @param cashRecord
     * @return 返回值JsonResp
     * @添加用户商家现金流水
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addCashRecord(@RequestBody CashRecord cashRecord) {
        log.debug("添加用户商家现金流水");
        cashRecordService.insert(cashRecord);
        return JsonResp.ok(cashRecord);
    }

    /**
     * @param cashRecord
     * @return 返回值JsonResp
     * @修改用户商家现金流水
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateCashRecord(@RequestBody CashRecord cashRecord) {
        log.debug("修改用户商家现金流水");
        if(cashRecord.getWithdrawStatus()==2){
          return JsonResp.fa("未接通");
        }else if (cashRecord.getWithdrawStatus()==3){
            cashRecordService.updateById(cashRecord);
        }

        return JsonResp.ok(cashRecord);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找用户商家现金流水
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectCashRecord(Long id) {
        log.debug("查找用户商家现金流水");
        CashRecord cashRecord = cashRecordService.selectById(id);
        return JsonResp.ok(cashRecord);
    }


    /**
     * 提现
     **/

    @RequestMapping(value = "/withdrawdeposit", method = RequestMethod.GET)
    public JsonResp withdrawdeposit(BigDecimal money){
        User user = userService.findLoginUser();
        if (user.getTotalassets().compareTo(money) >= 0) {
            EntityWrapper entityWrapper=new EntityWrapper();
            entityWrapper.eq("user_id",user.getId());
            entityWrapper.eq("status",1);
            UserAuthMsg userAuthMsg=userAuthMsgService.selectOne(entityWrapper);
            if (userAuthMsg!=null){
                CashRecord cashRecord = new CashRecord();
                cashRecord.setUserId(user.getId());
                cashRecord.setTransactionNum(OrderUtils.getOrderNo());
                cashRecord.setRecoedType(2);
                cashRecord.setMoneyType(1);
                cashRecord.setMoney(money);
                cashRecord.setStatus(null);
                cashRecord.setBankName(userAuthMsg.getBankName());
                cashRecord.setBankCard(userAuthMsg.getBankNum());
                cashRecord.setBankCardName(userAuthMsg.getRealName());
                cashRecord.setWithdrawStatus(1);
                cashRecord.setGmtDatetime(new Date());
                cashRecord.setUptDatetime(new Date());
                user.setTotalassets(user.getTotalassets().subtract(money));
                userService.updateById(user);
                Boolean bo = cashRecordService.insert(cashRecord);
                if (bo == false) {
                    return JsonResp.fa("提现失败");
                } else {
                    return JsonResp.ok("提交成功，正在审核。");
                }
            }else{
                return JsonResp.fa("未认证或未通过审核");
            }
        } else {
            return JsonResp.fa("超过可提现的余额");
        }
    }


    /***
     * 资产明细
     * */
    @RequestMapping(value = "/Capitaldetails", method = RequestMethod.GET)
    public JsonResp Capitaldetails(Page page, Integer type) {
        User user = userService.findLoginUser();
        Map map = new HashMap();
        map.put("type", type);
        Map maps = new HashMap();
        Page<CashRecord> cashRecordPage = null;
        BigDecimal mymoney = null;
        if (type == 1) {  //全部资产
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("user_id", user.getId());
            entityWrapper.orderBy("upt_datetime");
            cashRecordPage = cashRecordService.selectPage(page, entityWrapper);
            mymoney = user.getTotalassets();
        } else if (type == 2) {  //提现记录
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("user_id", user.getId());
            entityWrapper.eq("recoed_type", type);
            entityWrapper.orderBy("upt_datetime");
            cashRecordPage = cashRecordService.selectMapsPage(page, entityWrapper);
            mymoney = cashRecordService.inquiryorder(map);
        } else if (type == 3) { //充值记录
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.eq("user_id", user.getId());
            entityWrapper.eq("recoed_type", 1);
            entityWrapper.orderBy("upt_datetime");
            cashRecordPage = cashRecordService.selectMapsPage(page, entityWrapper);
            mymoney = cashRecordService.inquiryorder(map);
        } else {
            return JsonResp.fa("无返回");
        }
        maps.put("cashRecordPage", cashRecordPage);
        maps.put("mymoney", mymoney);
        return JsonResp.ok(maps);
    }


    /**
     * 出入金查询
     */
    @RequestMapping(value = "/Capitaldetailsadmin", method = RequestMethod.GET)
    public JsonResp Capitaldetailsadmin(Page page,String start,String end,Integer type) {
        Map map = new HashMap();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        map.put("type",type);
        map.put("start",start);
        map.put("end",end);
        List<CashRecord>  cashRecordList=cashRecordService.selectEntryandexit(map);
        Integer cash=cashRecordService.selectEntryandexitCount(map);
        return JsonResp.ok(new PageDto(page.getCurrent(),page.getSize(),cashRecordList,cash));
    }


    /**
     *    if (type==null){
     BigDecimal  userZZC=userService.totalAssets(map);
     maps.put("userZZC","存储平台总资产: "+userZZC);
     }else if(type==1){
     BigDecimal  userZZC=cashRecordService.totalAssetschongzhi(map);
     maps.put("userZZC","充值流水总资产: "+userZZC);
     }else if(type==2){
     BigDecimal  userZZC=cashRecordService.totalAssetschongzhi(map);
     maps.put("userZZC","提现流水总资产: "+userZZC);
     }else{
     BigDecimal  userZZC=cashRecordService.totalAssetschongzhi(map);
     maps.put("userZZC","待审批资产: "+userZZC);
     }
     * */



    /**
     * 后台资金明细
     */
    @RequestMapping(value = "/Capitaldetailsadmin2", method = RequestMethod.GET)
    public JsonResp Capitaldetailsadmin2(Page page, CashRecord cashRecord) {
        Map map = new HashMap();
        map.put("pageNo", (page.getCurrent() - 1) * page.getSize());
        map.put("pageSize", page.getSize());
        map.put("cashRecord", cashRecord);
        List<CashRecord> cashRecords = cashRecordService.selectusermoliy(map);
        Integer sun = cashRecordService.selectusermoliyCount(map);
        Map maps = new HashMap();
        maps.put("sun", sun);
           if (!cashRecords.isEmpty()){
                 for(CashRecord caah:cashRecords){
                     if (caah.getPayType()==5){
                        EntityWrapper entityWr=new EntityWrapper();
                         entityWr.eq("id",caah.getAdminid());
                         Admin admin=adminService.selectOne(entityWr);
                         caah.setAdmin(admin);
                     }
                 }
           }
        maps.put("cashRecordslist", cashRecords);
        BigDecimal userZZC = cashRecordService.totalAssetschongzhi(map);
        maps.put("userZZC", userZZC);
        return JsonResp.ok(maps);
    }


    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }


}
